#!/usr/bin/env python
# encoding: utf-8
# author: 04

from django.http import JsonResponse
from rest_framework import mixins, viewsets

from main.common.constants import ERROR_CODE as EC


class APIError(Exception):

    def __init__(self, code, message):
        return super().__init__(code, message)


class ApiToolPatch(object):
    """
    Patch: 对APIView 有效，需在继承列表中放在ApiView之前
    """

    def api_err(self, code: int, msg: str) -> APIError:
        return APIError(code, msg)

    def handle_exception(self, exc):
        if isinstance(exc, APIError):
            return JsonResponse({
                'status': 'error',
                'code': exc.args[0],
                'message': exc.args[1]
            })
        return super().handle_exception(exc)

    def get_clean_id(self, id_name, err_type=APIError):
        """ 尝试获取有效的 id_name 的数值,否则raise 错误，默认搭配APIError
        """
        id_value = self.request.query_params.get(id_name)
        if id_value:
            try:
                id_value = int(id_value)
                if id_value > 0:
                    return id_value
            except Exception:
                pass
        if err_type:
            raise err_type(EC.APP_BUG, f'无法获取有效的 {id_name} .')
        return None


class ModelViewSetWithoutDelete(mixins.CreateModelMixin,
                                mixins.ListModelMixin,
                                mixins.RetrieveModelMixin,
                                mixins.UpdateModelMixin,
                                viewsets.GenericViewSet):
    pass


class ModelViewSetWithoutDeleteUpdate(mixins.CreateModelMixin,
                                      mixins.ListModelMixin,
                                      mixins.RetrieveModelMixin,
                                      viewsets.GenericViewSet):
    pass
